package com.xuanwei.core.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xuanwei.core.exception.XwException;
import com.xuanwei.core.service.IXwProductLabelService;
import com.xuanwei.dao.entity.XwProductLabel;
import com.xuanwei.dao.mapper.XwProductLabelMapper;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author mjy
 * @since 2019-04-25
 */
@Service
public class XwProductLabelServiceImpl extends ServiceImpl<XwProductLabelMapper, XwProductLabel> implements IXwProductLabelService {


    @Override
    public void addOrUpdate(Integer id, String name,String color, Integer operationId) {
        XwProductLabel label = new XwProductLabel();
        label.setId(id);
        label.setColor(color);
        label.setName(name);
        label.setOperationId(operationId);
        label.setUpdateTime(LocalDateTime.now());
        XwProductLabel productLabel = getOne(new QueryWrapper<XwProductLabel>()
                .select("id,`name`").eq("`name`", name));
        if (id == null) {
            if(productLabel!=null){
                throw new XwException("已存在该标签名");
            }
            label.setCreateTime(LocalDateTime.now());
            getBaseMapper().insert(label);
        } else {
            if(!Objects.isNull(productLabel) &&productLabel.getId()!=id){
                throw new XwException("已存在该标签名");
            }
            XwProductLabel _label = getBaseMapper().selectById(id);
            if (_label == null) {
                throw new XwException("没有该标签");
            }
            getBaseMapper().updateById(label);
        }

    }


    @Override
    public List<XwProductLabel> findList() {

        return getBaseMapper().selectList(new QueryWrapper<XwProductLabel>()
                .select("id,`name`,color,create_time"));
    }

}
